package com.openlogic.common.plugins.db.mysql.param;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.plugins.db.api.datasource.AbstractDataSourceProcessor;
import com.openlogic.common.plugins.db.api.datasource.DataSourceProcessor;
import com.openlogic.common.plugins.db.api.dto.BaseDataSourceParamDto;
import com.openlogic.common.plugins.db.api.utils.JSONUtils;
import com.openlogic.common.plugins.db.api.utils.PasswordUtils;
import com.openlogic.common.plugins.spi.constants.DataSourceConstants;
import com.openlogic.common.plugins.spi.enums.DbType;
import com.openlogic.datasource.api.param.BaseConnectionParam;
import com.openlogic.datasource.api.param.ConnectionParam;

/**
 * @ClassName: MySQLDataSourceProcessor
 * @Description: MYSQL数据源处理器插件
 * @author weiyongpeng
 * @date 2025年1月26日 下午8:37:00
 */
public class MySQLDataSourceProcessor extends AbstractDataSourceProcessor {

	private final Logger logger = LoggerFactory.getLogger(MySQLDataSourceProcessor.class);

	private static final String ALLOW_LOAD_LOCAL_IN_FILE_NAME = "allowLoadLocalInfile";

	private static final String AUTO_DESERIALIZE = "autoDeserialize";

	private static final String ALLOW_LOCAL_IN_FILE_NAME = "allowLocalInfile";

	private static final String ALLOW_URL_IN_LOCAL_IN_FILE_NAME = "allowUrlInLocalInfile";

	private static final String APPEND_PARAMS = "allowLoadLocalInfile=false&autoDeserialize=false&allowLocalInfile=false&allowUrlInLocalInfile=false";

	private static final String PAGE_SQL_TEMPLATE = "{0} LIMIT {1} OFFSET {2} ";

	private static final String COUNT_SQL_TEMPLATE = "SELECT COUNT(1) FROM {0} ";

	@Override
	public String getDatasourceDriver() {
		return DataSourceConstants.COM_MYSQL_CJ_JDBC_DRIVER;
	}

	@Override
	public String getValidationQuery() {
		return DataSourceConstants.MYSQL_VALIDATION_QUERY;
	}

	@Override
	public String getJdbcUrl(ConnectionParam connectionParam) {
		MySQLConnectionParam mysqlConnectionParam = new MySQLConnectionParam(); // (MySQLConnectionParam)
																				// connectionParam;
		try {
			BeanUtils.copyProperties(mysqlConnectionParam, connectionParam);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		String jdbcUrl = mysqlConnectionParam.getJdbcUrl();
		if (!StringUtils.isEmpty(mysqlConnectionParam.getOther())) {
			return String.format("%s?%s&%s", jdbcUrl, mysqlConnectionParam.getOther(), APPEND_PARAMS);
		}
		return String.format("%s?%s", jdbcUrl, APPEND_PARAMS);
	}

	@Override
	public Connection getConnection(ConnectionParam connectionParam) throws ClassNotFoundException, SQLException {
		MySQLConnectionParam mysqlConnectionParam = new MySQLConnectionParam(); // (MySQLConnectionParam)
																				// connectionParam;
		try {
			BeanUtils.copyProperties(mysqlConnectionParam, connectionParam);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		Class.forName(getDatasourceDriver());
		String user = mysqlConnectionParam.getUser();
		if (user.contains(AUTO_DESERIALIZE)) {
			logger.warn("sensitive param : {} in username field is filtered", AUTO_DESERIALIZE);
			user = user.replace(AUTO_DESERIALIZE, "");
		}
		String password = PasswordUtils.decodePassword(mysqlConnectionParam.getPassword());
		if (password.contains(AUTO_DESERIALIZE)) {
			logger.warn("sensitive param : {} in password field is filtered", AUTO_DESERIALIZE);
			password = password.replace(AUTO_DESERIALIZE, "");
		}

		return DriverManager.getConnection(getJdbcUrl(connectionParam), user, password);
	}

	@Override
	public BaseDataSourceParamDto castDatasourceParamDTO(String paramJson) {
		return JSONUtils.parseObject(paramJson, MySQLDataSourceParamDTO.class);
	}

	@Override
	public String columns(String dbName, String tableName) {
		return "select column_name AS COLNAME, ordinal_position AS COLPOSITION, column_default AS DATADEFAULT, is_nullable AS NULLABLE, data_type AS DATATYPE, "
				+ "character_maximum_length AS DATALENGTH, numeric_precision AS DATAPRECISION, numeric_scale AS DATASCALE, column_key AS COLKEY, column_comment AS COLCOMMENT "
				+ "from information_schema.columns where table_schema = '" + dbName + "' and table_name = '" + tableName
				+ "' order by ordinal_position ";
	}

	@Override
	public String tables(String dbName) {
		return "SELECT table_name AS TABLENAME, table_comment AS TABLECOMMENT FROM information_schema.tables where table_schema = '"
				+ dbName + "' ";
	}

	@Override
	public BaseConnectionParam createConnectionParams(BaseDataSourceParamDto dataSourceParam) {
		MySQLDataSourceParamDTO mysqlDatasourceParam = (MySQLDataSourceParamDTO) dataSourceParam;
		String address = String.format("%s%s:%s", DataSourceConstants.JDBC_MYSQL, mysqlDatasourceParam.getHost(),
				mysqlDatasourceParam.getPort());
		String jdbcUrl = String.format("%s/%s", address, mysqlDatasourceParam.getDatabase());

		MySQLConnectionParam mysqlConnectionParam = new MySQLConnectionParam();
		mysqlConnectionParam.setJdbcUrl(jdbcUrl);
		mysqlConnectionParam.setDatabase(mysqlDatasourceParam.getDatabase());
		mysqlConnectionParam.setAddress(address);
		mysqlConnectionParam.setUser(mysqlDatasourceParam.getUserName());
		mysqlConnectionParam.setPassword(PasswordUtils.encodePassword(mysqlDatasourceParam.getPassword()));
		mysqlConnectionParam.setDriverClassName(getDatasourceDriver());
		mysqlConnectionParam.setValidationQuery(getValidationQuery());
		mysqlConnectionParam.setOther(transformOther(mysqlDatasourceParam.getOther()));
		mysqlConnectionParam.setProps(mysqlDatasourceParam.getOther());

		return mysqlConnectionParam;
	}

	private String transformOther(Map<String, String> paramMap) {
		if (MapUtils.isEmpty(paramMap)) {
			return null;
		}
		Map<String, String> otherMap = new HashMap<>();
		paramMap.forEach((k, v) -> {
			if (!checkKeyIsLegitimate(k)) {
				return;
			}
			otherMap.put(k, v);
		});
		if (MapUtils.isEmpty(otherMap)) {
			return null;
		}
		StringBuilder stringBuilder = new StringBuilder();
		otherMap.forEach((key, value) -> stringBuilder.append(String.format("%s=%s&", key, value)));
		return stringBuilder.toString();
	}

	@Override
	public DbType getDbType() {
		return DbType.MYSQL;
	}

	@Override
	public DataSourceProcessor create() {
		return new MySQLDataSourceProcessor();
	}

	private static boolean checkKeyIsLegitimate(String key) {
		return !key.contains(ALLOW_LOAD_LOCAL_IN_FILE_NAME) && !key.contains(AUTO_DESERIALIZE)
				&& !key.contains(ALLOW_LOCAL_IN_FILE_NAME) && !key.contains(ALLOW_URL_IN_LOCAL_IN_FILE_NAME);
	}

	@Override
	public String parsePageSql(String orignSql, Integer page, Integer pageSize) {
		Integer perPage = pageSize; // 每页大小
		Integer offset = (page - 1) * perPage; // 偏移量
		return MessageFormat.format(PAGE_SQL_TEMPLATE, orignSql, perPage, offset);
	}

	@Override
	public String parseCountSql(String tableName) {
		return MessageFormat.format(COUNT_SQL_TEMPLATE, tableName);
	}

}